package com.light.mytext.mycustomview

import android.os.Build
import android.os.Bundle
import android.util.DisplayMetrics
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.widget.LinearLayout
import androidx.appcompat.app.AppCompatActivity
import com.light.mytext.R
import com.light.mytext.model.LocationM
import com.light.mytext.model.PayEven
import com.light.mytext.utiles.ParamsUtils
import com.light.mytext.utiles.ScreenUtils
import com.light.mytext.utiles.SystemBarTintManager
import com.light.mytext.utiles.ToastUtils
import kotlinx.android.synthetic.main.activity_line_point.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 1、addview多个但是只显示一个
 * 把LinearLayout改成FrameLayout
 * 2、使用FrameLayout之后自定义布局中onMeasure设置宽高不起作用，需要改回LinearLayout
 *  折中方式：对自定义View使用layoutParams动态设置宽高
 * 3、拖动时候下部一直可以超出屏幕
 *  需要减去页面自带的标题栏ToolBar+状态栏的高度
 * 4、坐标单位为dp   可把坐标转为marginTop   marginleft
 * 5、自定义view设置可拖动时候  如果使用layout（l,t,r,b）的时候 每次addview，都会重新刷新所有已添加控件的位置，
 * 即已经添加的并且移动改变位置的,再次addview新view的时候，会被刷新位置至默认处
 *
 */
class LinePointActivity : AppCompatActivity(), View.OnTouchListener, View.OnClickListener {
    //view中心坐标
    var strX = arrayOf("193", "455", "234", "511", "545")
    var strY = arrayOf("288", "432", "650", "176", "782")
    var startLineY = arrayOf("100", "150", "200", "250", "300")
    var num = 0
    var linnum = 0
    var recnum = 0
    var lastX = 0
    var lastY = 0
    private var dm: DisplayMetrics? = null
    var screenWidth = 0
    var screenHeight = 0

    //父布局
    var waiWidth = 0
    var waiHeight = 0


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requestWindowFeature(Window.FEATURE_NO_TITLE);//隐藏标题栏
        getWindow().setFlags(
            WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN
        );//隐藏状态栏
        setContentView(R.layout.activity_line_point)
        EventBus.getDefault().register(this)
        initSystemBar()
        dm = resources.displayMetrics
        screenWidth = ScreenUtils.getWidth(this)
        screenHeight = ScreenUtils.getHeight(this)
        init()
        init_Listener()
    }

    fun init() {
        //父布局范围
        li_wai.post(Runnable {
            waiWidth = li_wai.width
            waiHeight = li_wai.height
            Log.w("tv_width", "" + li_wai.getWidth())
            Log.w("tv_height", "" + li_wai.getHeight())
        })
    }


    fun init_Listener() {
        tv_addcursor.setOnClickListener(this)
        tv_addline.setOnClickListener(this)
        tv_addrectangle.setOnClickListener(this)
    }

    /**
     * 添加光标
     */
    fun addCurSor() {
//        for (i in strX.indices) {
        if (num < strX.size) {
            var cursorView =
                CurSorView(this, waiWidth, waiHeight, num + 1)
            var cLayoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            )
            cLayoutParams.setMargins(
                strX[num].toInt() - 75,
                strY[num].toInt() - 75,
                0,
                0
            )//margin是相对于边的  减去view/2  即相当于中心的位置
            cursorView.layoutParams = cLayoutParams
//        cursorView.setBackgroundColor(resources.getColor(R.color.orange))
            li_wai.addView(cursorView)
            num++
        }
//        }
    }

    /**
     * 添加直线
     */
    fun addLine() {
        if (linnum < startLineY.size) {
            var lineView =
                LineView2(this, ScreenUtils.getWidth(this))
            /*var lLayoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            )
            lLayoutParams.setMargins(
                0,
                startLineY[linnum].toInt(),
                0,
                ScreenUtils.getHeight(this) - 50 - startLineY[linnum].toInt() - 15
            )//margin是相对于边的  减去view/2  即相当于中心的位置
            lineView.layoutParams = lLayoutParams*/
            lineView.setBackgroundColor(resources.getColor(R.color.orange))
            li_wai.addView(lineView)
            linnum++
        }
    }

    /**
     * 添加矩形
     */
    fun addRectangle() {
        if (recnum < 3) {
            var RectangleView =
                MyRectangleView(this, waiWidth, waiHeight, recnum)
            RectangleView.id = recnum
            RectangleView.setBackgroundColor(resources.getColor(R.color.orange))
            li_wai.addView(RectangleView)
            var bean = LocationM()
            bean.id = recnum
            bean.left = 0
            bean.top = 0
            ParamsUtils.listLocation.add(bean)
            recnum++
        }

    }


    override fun onTouch(v: View, event: MotionEvent): Boolean {
        val screenWidth: Int = dm!!.widthPixels
        val screenHeight: Int = dm!!.heightPixels
        if (v.tag == "tag") {
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    lastX = event.rawX.toInt() // 获取触摸事件触摸位置的原始X坐标
                    lastY = event.rawY.toInt()
                    Log.i(
                        "MotionEvent",
                        v.tag.toString() + "height==" + v.height + "width==" + v.width + "v.left==" + v.left
                    )
                    ToastUtils.show(this, "top==" + v.top + "bottom==" + v.bottom)
                }
                MotionEvent.ACTION_MOVE -> {
                    val dx: Int = event.rawX.toInt() - lastX
                    val dy: Int = event.rawY.toInt() - lastY
                    var l = v.left + dx
                    var r = l + v.width;
                    var t = v.top + dy
                    var b = t + v.height;
                    ToastUtils.show(this, "top==" + v.top + "bottom==" + v.bottom)
                    // 下面判断移动是否超出屏幕
                    if (l < 0) {
                        l = 0
                        r = l + v.width
                    }
                    if (t < 0) {
                        t = 0
                        b = t + v.height
                    }
                    if (r > screenWidth) {
                        r = screenWidth
                        l = r - v.width
                    }
                    if (b > screenHeight) {
                        b = screenHeight
                        t = b - v.height
                    }
                    v.layout(l, t, r, b)
                    Log.i(
                        "Move",
                        "Move==dx==" + dx + "\r\ndy==" + dy + "\r\nl==" + l + "\r\nb==" + b + "\r\nr==" + r + "\r\nb==" + b
                    )
                    lastX = event.rawX.toInt()
                    lastY = event.rawY.toInt()
                    v.postInvalidate()
                }
                MotionEvent.ACTION_UP -> {
                }
                else -> {
                }
            }
        }
        return true
    }

    /**
     * 隐藏状态栏
     */
    fun initSystemBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setTranslucentStatus(true)
        }
        val tintManager = SystemBarTintManager(this)
        tintManager.isStatusBarTintEnabled = false
    }

    private fun setTranslucentStatus(on: Boolean) {
        val win = window
        val winParams = win.attributes
        val bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
        if (on) {
            winParams.flags = winParams.flags or bits
        } else {
            winParams.flags = winParams.flags and bits.inv()
        }
        win.attributes = winParams
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.tv_addcursor -> {//添加光标
                addCurSor()
            }
            R.id.tv_addline -> {//添加直线
                addLine()
            }
            R.id.tv_addrectangle -> {//添加矩形
                addRectangle()
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessEvent(even: PayEven) {
        if ("改变选中状态" == even.str1) {



        }
    }

}